<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Http\Traits\CheckPermission;
use App\Http\Traits\LogOperation;
use App\Models\Permission;
use App\Models\User;
use App\Services\TokenService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    use CheckPermission, LogOperation;

    protected $tokenService;
    protected $userService;
    protected $resource = 'users';

    public function __construct(TokenService $tokenService, UserService $userService)
    {
        $this->tokenService = $tokenService;
        $this->userService = $userService;
        $this->middleware('auth.api');
    }

    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $filters = $request->only(['username', 'status', 'dept_id']);
        $query = $this->userService->buildQuery($filters);
        $users = $query->paginate($this->getPageSize($request));

        // 批量获取在线用户ID，避免N+1查询
        $onlineUserIds = \App\Models\OnlineUser::pluck('user_id')->unique()->toArray();
        
        // 使用Resource格式化分页数据，包括时间字段
        $users->setCollection(
            $users->getCollection()->map(function ($user) use ($onlineUserIds) {
                $user->is_online = in_array($user->id, $onlineUserIds);
                return (new UserResource($user))->resolve(request());
            })
        );

        return $this->success($users, '获取成功');
    }

    /**
     * 批量删除用户
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchDestroy(Request $request)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:users,id',
        ]);

        $currentUserId = auth()->id();
        $ids = $request->ids;

        // 不能删除自己
        if (in_array($currentUserId, $ids)) {
            return $this->error('不能删除自己', 400);
        }

        // 检查每个数据的权限
        foreach ($ids as $id) {
            $this->authorizeDataPermission($this->resource, Permission::ACTION_DELETE, $id);
        }

        // 记录删除前的用户信息
        $usersToDelete = User::whereIn('id', $ids)->get();
        
        $count = 0;
        foreach ($ids as $id) {
            $user = User::find($id);
            if ($user) {
                // 记录每个用户的删除操作
                $this->logDelete($this->resource, $user, "批量删除用户: {$user->username}", $request);
                $this->userService->delete($user);
                $count++;
            }
        }

        return $this->success(['deleted_count' => $count], "成功删除 {$count} 个用户");
    }

    /**
     * 批量更新用户状态
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchUpdateStatus(Request $request)
    {
        // 检查更新权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_UPDATE);

        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:users,id',
            'status' => 'required|integer|in:' . implode(',', [
                \App\Models\User::STATUS_DISABLED,
                \App\Models\User::STATUS_ENABLED,
            ]),
        ]);

        // 检查每个数据的权限
        foreach ($request->ids as $id) {
            $this->authorizeDataPermission($this->resource, Permission::ACTION_UPDATE, $id);
        }

        // 记录更新前的数据
        $usersBeforeUpdate = User::whereIn('id', $request->ids)->get()->keyBy('id');
        
        $count = User::whereIn('id', $request->ids)
            ->update(['status' => $request->status]);

        // 记录每个用户的更新操作
        if ($count > 0) {
            $usersAfterUpdate = User::whereIn('id', $request->ids)->get()->keyBy('id');
            foreach ($request->ids as $id) {
                $userBefore = $usersBeforeUpdate->get($id);
                $userAfter = $usersAfterUpdate->get($id);
                if ($userBefore && $userAfter) {
                    // 只记录状态有变化的用户
                    if ($userBefore->status != $userAfter->status) {
                        $this->logUpdate(
                            $this->resource,
                            $userAfter,
                            $userBefore->toArray(),
                            "批量更新用户状态: {$userAfter->username}",
                            $request
                        );
                    }
                }
            }
        }

        return $this->success(['updated_count' => $count], "成功更新 {$count} 个用户状态");
    }

    /**
     * 导出用户数据
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function export(Request $request)
    {
        // 检查导出权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_EXPORT);

        $filters = $request->only(['username', 'status', 'dept_id']);
        $query = $this->userService->buildQuery($filters);
        $users = $query->with(['department', 'roles'])->get();
        
        $userCount = $users->count();

        try {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置表头
            $headers = ['ID', '用户名', '昵称', '邮箱', '手机', '状态', '最大设备数', '部门', '角色', '创建时间'];
            $column = 'A';
            foreach ($headers as $header) {
                $sheet->setCellValue($column . '1', $header);
                $sheet->getStyle($column . '1')->getFont()->setBold(true);
                $column++;
            }

            // 填充数据
            $row = 2;
            foreach ($users as $user) {
                $sheet->setCellValue('A' . $row, $user->id);
                $sheet->setCellValue('B' . $row, $user->username);
                $sheet->setCellValue('C' . $row, $user->nickname);
                $sheet->setCellValue('D' . $row, $user->email);
                $sheet->setCellValue('E' . $row, $user->phone);
                $sheet->setCellValue('F' . $row, $user->status == 1 ? '启用' : '禁用');
                $sheet->setCellValue('G' . $row, $user->max_devices ?? 1);
                $sheet->setCellValue('H' . $row, $user->department ? $user->department->name : '');
                $sheet->setCellValue('I' . $row, $user->roles->pluck('name')->join(','));
                $sheet->setCellValue('J' . $row, $user->created_at?->format('Y-m-d H:i:s'));
                $row++;
            }

            // 自动调整列宽
            foreach (range('A', 'J') as $col) {
                $sheet->getColumnDimension($col)->setAutoSize(true);
            }

            // 生成Excel文件
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $fileName = '用户列表_' . date('YmdHis') . '.xlsx';
            $filePath = storage_path('app/temp/' . $fileName);
            
            // 确保目录存在
            if (!file_exists(storage_path('app/temp'))) {
                mkdir(storage_path('app/temp'), 0755, true);
            }
            
            $writer->save($filePath);

            // 记录导出操作（在返回响应前记录，确保日志被保存）
            try {
                $this->logExport($this->resource, $userCount, "导出用户数据（{$userCount}条）", $request);
            } catch (\Exception $logException) {
                // 日志记录失败不应影响文件下载
                \Log::error('导出操作日志记录失败: ' . $logException->getMessage());
            }

            return response()->download($filePath, $fileName)->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            // 导出失败时也记录日志
            try {
                $this->logOperation(
                    'export',
                    $this->resource,
                    null,
                    "导出用户数据失败: " . $e->getMessage(),
                    null,
                    ['error' => $e->getMessage(), 'count' => $userCount],
                    $request
                );
            } catch (\Exception $logException) {
                \Log::error('导出失败日志记录失败: ' . $logException->getMessage());
            }
            
            return $this->error('导出失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 导入用户数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function import(Request $request)
    {
        // 检查导入权限（使用create权限，因为导入也是创建用户）
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_CREATE);

        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240', // 10MB
        ]);

        try {
            $file = $request->file('file');
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getRealPath());
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray();

            if (count($rows) < 2) {
                return $this->error('Excel文件为空或格式不正确', 400);
            }

            // 跳过表头，从第二行开始
            $headers = $rows[0];
            $data = array_slice($rows, 1);

            $successCount = 0;
            $failCount = 0;
            $errors = [];

            DB::beginTransaction();
            try {
                foreach ($data as $index => $row) {
                    if (empty($row[1])) { // 如果用户名为空，跳过
                        continue;
                    }

                    try {
                        // 解析状态（第6列，索引5）- 状态列应该是"启用"或"禁用"
                        $status = 1;
                        if (isset($row[5])) {
                            $statusValue = trim($row[5]);
                            if ($statusValue === '禁用' || $statusValue === '0' || $statusValue === 0 || strtolower($statusValue) === 'disabled') {
                                $status = 0;
                            }
                        }

                        // 解析最大设备数（第7列，索引6）- 如果存在
                        $maxDevices = 1; // 默认1台
                        if (isset($row[6]) && !empty($row[6])) {
                            $maxDevicesValue = (int)trim($row[6]);
                            if ($maxDevicesValue >= 1 && $maxDevicesValue <= 5) {
                                $maxDevices = $maxDevicesValue;
                            }
                        }

                        // 验证邮箱格式
                        $email = !empty($row[3]) ? trim($row[3]) : null;
                        if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            throw new \Exception('邮箱格式不正确');
                        }

                        // 查找部门（第8列，索引7，如果最大设备数存在则后移）
                        $department = null;
                        $deptColumnIndex = isset($row[6]) && is_numeric(trim($row[6])) ? 7 : 6;
                        if (isset($row[$deptColumnIndex]) && !empty($row[$deptColumnIndex])) {
                            $department = \App\Models\Department::where('name', trim($row[$deptColumnIndex]))->first();
                        }

                        // 查找角色（第9列，索引8，如果最大设备数存在则后移）
                        $roleIds = [];
                        $roleColumnIndex = isset($row[6]) && is_numeric(trim($row[6])) ? 8 : 7;
                        if (isset($row[$roleColumnIndex]) && !empty($row[$roleColumnIndex])) {
                            $roleNames = array_filter(array_map('trim', explode(',', $row[$roleColumnIndex])));
                            if (!empty($roleNames)) {
                                $roles = \App\Models\Role::whereIn('name', $roleNames)->get();
                                $roleIds = $roles->pluck('id')->toArray();
                            }
                        }

                        // 创建或更新用户
                        $userData = [
                            'nickname' => !empty($row[2]) ? trim($row[2]) : trim($row[1]),
                            'email' => $email,
                            'phone' => !empty($row[4]) ? trim($row[4]) : null,
                            'status' => $status,
                            'max_devices' => $maxDevices,
                            'dept_id' => $department ? $department->id : null,
                        ];

                        $username = trim($row[1]);
                        
                        // 验证用户名不包含'admin'字符（不区分大小写）
                        if (preg_match('/admin/i', $username)) {
                            throw new \Exception('用户名不能包含"admin"字符，admin为系统内置用户');
                        }
                        
                        $user = User::where('username', $username)->first();
                        if ($user) {
                            // 更新现有用户，不更新密码
                            $user->update($userData);
                        } else {
                            // 创建新用户，设置默认密码
                            $userData['password'] = Hash::make('123456');
                            $userData['username'] = $username;
                            $user = User::create($userData);
                        }

                        // 同步角色
                        if (!empty($roleIds)) {
                            $user->roles()->sync($roleIds);
                        }

                        $successCount++;
                    } catch (\Exception $e) {
                        $failCount++;
                        $username = $row[1] ?? '未知';
                        $errors[] = "第" . ($index + 2) . "行：{$username} - " . $e->getMessage();
                    }
                }
                
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->error('导入失败：' . $e->getMessage(), 500);
            }

            // 记录导入操作
            $this->logImport(
                $this->resource,
                $successCount,
                $failCount,
                "导入用户数据（成功:{$successCount}条，失败:{$failCount}条）",
                $request
            );

            return $this->success([
                'success_count' => $successCount,
                'fail_count' => $failCount,
                'errors' => $errors,
            ], "导入完成，成功：{$successCount}条，失败：{$failCount}条");
        } catch (\Exception $e) {
            return $this->error('导入失败：' . $e->getMessage(), 500);
        }
    }

    public function store(StoreUserRequest $request)
    {
        // 检查新增权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_CREATE);

        $user = $this->userService->create($request->validated());
        
        // 记录创建操作
        $this->logCreate($this->resource, $user, "创建用户: {$user->username}", $request);
        
        return $this->success(new UserResource($user), '创建成功');
    }

    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);
        
        // 检查数据权限
        $this->authorizeDataPermission($this->resource, Permission::ACTION_VIEW, $id);

        $user = User::with(['roles', 'department'])->findOrFail($id);
        return $this->success(new UserResource($user), '获取成功');
    }

    public function update(UpdateUserRequest $request, $id)
    {
        // 检查编辑权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_UPDATE);
        
        // 检查数据权限
        $this->authorizeDataPermission($this->resource, Permission::ACTION_UPDATE, $id);

        $user = User::findOrFail($id);
        // 保存更新前的数据
        $originalData = $user->toArray();
        
        $user = $this->userService->update($user, $request->validated());
        
        // 记录更新操作
        $this->logUpdate($this->resource, $user, $originalData, "更新用户: {$user->username}", $request);
        
        return $this->success(new UserResource($user), '更新成功');
    }

    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);
        
        // 检查数据权限
        $this->authorizeDataPermission($this->resource, Permission::ACTION_DELETE, $id);

        $user = User::findOrFail($id);

        if ($user->id === auth()->id()) {
            return $this->error('不能删除自己', 400);
        }

        // 记录删除操作（在删除前记录）
        $this->logDelete($this->resource, $user, "删除用户: {$user->username}", request());
        
        $this->userService->delete($user);
        return $this->success(null, '删除成功');
    }

    public function forceLogout(User $user)
    {
        $currentUser = auth()->user();

        if (!$currentUser->isAdmin()) {
            return $this->forbidden('无权限操作');
        }

        $this->tokenService->removeAll($user->id);
        \App\Models\OnlineUser::where('user_id', $user->id)->delete();

        return $this->success(null, '强制登出成功');
    }
}

